package com.xxx.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO server
 */
@Slf4j
public class BIOServer {

    public static void main(String[] args) throws IOException {
        // 创建一个线程池，用来处理客户端请求
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);  // 监听6666端口
        System.out.println("服务端启动了");

        // 循环等待客户端的连接
        while (true) {
            final Socket socket = serverSocket.accept();
            System.out.println("有一个客户端连接过来");

            // 启动一个线程处理客户端请求
            executorService.execute(() -> {
                try {
                    handle(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    // 处理socket请求
    private static void handle(Socket socket) throws IOException {
        System.out.println("当前线程：" + Thread.currentThread().getName());
        // 创建一个byte数组，用来接收客户端发送过来的信息
        byte [] bytes = new byte[1024];
        // 从socket里读取数组
        InputStream inputStream = socket.getInputStream();
        // 循环读取输入流
        while (true) {
            // 将数组读取到byte数组中
            int read = inputStream.read(bytes);  // read表示读取的byte数组长度，-1表示读取完成
            if(read != -1) { // 未读取完成
                System.out.println("读取到客户端发送过来的数据：" + new String(bytes, 0, read, StandardCharsets.UTF_8));
            } else {  // 读取完成
                break;
            }
        }
        socket.close();
    }
}
